'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Button, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Dialog, DialogTitle, DialogContent, DialogActions, TextField, Stack, IconButton, Alert, Snackbar } from '@mui/material';
import { DataGrid } from '@mui/x-data-grid';
import { useForm, Controller } from 'react-hook-form';
import MenuItem from '@mui/material/MenuItem';
import QuestionForm from '@/components/QuestionForm';
import { Question, getQuestions, createQuestion, updateQuestion, deleteQuestion } from '@/api/questions';

export default function QuestionsPage() {
  const router = useRouter();
  const [questions, setQuestions] = useState<Question[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingQuestion, setEditingQuestion] = useState<Question | null>(null);
  const { control, handleSubmit, reset, watch } = useForm({
    defaultValues: {
      type: 'CHOICE',
      subject: '',
      content: '',
      options: [],
      answer: '',
      explanation: '',
      score: 1.0
    }
  });
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' });

  useEffect(() => {
    // 检查用户角色并获取题目列表
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    if (user.role === 'TEACHER') {
      fetchQuestions();
    } else {
      setSnackbar({ open: true, message: '只有教师才能访问题库管理页面', severity: 'error' });
      router.push('/');
    }
  }, [router]); // 只在组件挂载和路由变化时执行

  const fetchQuestions = async () => {
    try {
      const data = await getQuestions();
      // 确保数据格式正确
      const formattedData = data.map(question => ({
        ...question,
        id: question.id || Math.random(), // 确保每行都有唯一id
        type: question.type || 'UNKNOWN' // 确保type字段存在
      }));
      setQuestions(formattedData);
    } catch (error) {
      setSnackbar({
        open: true,
        message: '获取题目列表失败',
        severity: 'error'
      });
    }
  };


  const handleCreate = async (values: any) => {
    try {
      let formattedValues = { ...values };
      
      if (values.type === 'CHOICE') {
        const optionsArray = typeof values.options === 'string'
          ? values.options.split('\n').filter(Boolean)
          : (Array.isArray(values.options) ? values.options : []);

        if (optionsArray.length < 2 || optionsArray.length > 4) {
          setSnackbar({
            open: true,
            message: optionsArray.length < 2 ? '选择题至少需要两个选项' : '选项数量不能超过4个',
            severity: 'error'
          });
          return;
        }

        formattedValues.options = optionsArray;
        // 确保答案是选项的索引对应的字母
        if (values.answer) {
          const answerIndex = values.answer.charCodeAt(0) - 65;
          if (answerIndex < 0 || answerIndex >= optionsArray.length) {
            setSnackbar({ open: true, message: '请选择有效的答案选项', severity: 'error' });
            return;
          }
        }
      } else {
        formattedValues.options = [];
      }

      // 验证判断题答案格式
      if (values.type === 'TRUE_FALSE') {
        if (!['true', 'false'].includes(values.answer.toLowerCase())) {
          setSnackbar({ open: true, message: '判断题答案必须为true或false', severity: 'error' });
          return;
        }
        formattedValues.answer = values.answer.toLowerCase();
      }

      await createQuestion(formattedValues);
      setSnackbar({ open: true, message: '创建题目成功', severity: 'success' });
      setIsModalVisible(false);
      reset();
      fetchQuestions();
    } catch (error) {
      console.error('创建题目失败:', error);
      setSnackbar({ open: true, message: '创建题目失败', severity: 'error' });
    }
  };

  const handleUpdate = async (values: any) => {
    if (!editingQuestion) return;
  
    try {
      let formattedValues = { ...values };
      
      if (values.type === 'CHOICE') {
        const optionsArray = typeof values.options === 'string'
          ? values.options.split('\n').filter(Boolean)
          : (Array.isArray(values.options) ? values.options : []);

        if (optionsArray.length < 2 || optionsArray.length > 4) {
          setSnackbar({
            open: true,
            message: optionsArray.length < 2 ? '选择题至少需要两个选项' : '选项数量不能超过4个',
            severity: 'error'
          });
          return;
        }

        formattedValues.options = optionsArray;
        // 确保答案是选项的索引对应的字母
        if (values.answer) {
          const answerIndex = values.answer.charCodeAt(0) - 65;
          if (answerIndex < 0 || answerIndex >= optionsArray.length) {
            setSnackbar({ open: true, message: '请选择有效的答案选项', severity: 'error' });
            return;
          }
        }
      } else {
        formattedValues.options = [];
      }

      // 验证判断题答案格式
      if (values.type === 'TRUE_FALSE') {
        if (!['true', 'false'].includes(values.answer.toLowerCase())) {
          setSnackbar({ open: true, message: '判断题答案必须为true或false', severity: 'error' });
          return;
        }
        formattedValues.answer = values.answer.toLowerCase();
      }

      await updateQuestion(editingQuestion.id, formattedValues);
      setSnackbar({ open: true, message: '更新题目成功', severity: 'success' });
      setIsModalVisible(false);
      setEditingQuestion(null);
      reset();
      fetchQuestions();
    } catch (error) {
      setSnackbar({ open: true, message: '更新题目失败', severity: 'error' });
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await deleteQuestion(id);
      setSnackbar({ open: true, message: '删除题目成功', severity: 'success' });
      fetchQuestions();
    } catch (error) {
      setSnackbar({ open: true, message: '删除题目失败', severity: 'error' });
    }
  };

  const columns = [
    {
      field: 'subject',
      headerName: '科目',
      flex: 0.2,
      minWidth: 120,
      headerAlign: 'center',
      align: 'center'
    },
    {
      field: 'type',
      headerName: '题目类型',
      flex: 0.2,
      minWidth: 120,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params: any) => {
        try {
          if (!params?.row?.type) return '未知类型';
          const typeMap = {
            'CHOICE': '选择题',
            'TRUE_FALSE': '判断题',
            'FILL_BLANK': '填空题',
            'SHORT_ANSWER': '简答题'
          };
          return typeMap[params.row.type] || '未知类型';
        } catch (error) {
          console.error('处理题目类型数据时出错:', error);
          return '未知类型';
        }
      }
    },
    {
      field: 'content',
      headerName: '题目内容',
      flex: 0.4,
      minWidth: 300,
      headerAlign: 'center',
      align: 'center'
    },
    {
      field: 'answer',
      headerName: '答案',
      flex: 0.2,
      minWidth: 150,
      headerAlign: 'center',
      align: 'center'
    },
    {
      field: 'score',
      headerName: '分值',
      flex: 0.1,
      minWidth: 80,
      renderCell: (params: any) => (
        <div>{params.row.score || 1.0}</div>
      )
    },
    {
      field: 'actions',
      headerName: '操作',
      flex: 0.2,
      minWidth: 150,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params: any) => (
        <Stack direction="row" spacing={1}>
          <Button
            variant="contained"
            size="small"
            onClick={() => {
              const questionData = { ...params.row };
              if (questionData.type === 'CHOICE') {
                // 确保选项数据是数组格式
                questionData.options = Array.isArray(questionData.options)
                  ? questionData.options
                  : typeof questionData.options === 'string'
                    ? (questionData.options.startsWith('[') ? JSON.parse(questionData.options) : questionData.options.split('\n').filter(Boolean))
                    : [];
              }
              setEditingQuestion(questionData);
              reset({
                ...questionData,
                options: questionData.type === 'CHOICE' ? questionData.options.join('\n') : questionData.options
              });
              setIsModalVisible(true);
            }}
          >
            编辑
          </Button>
          <Button
            variant="contained"
            color="error"
            size="small"
            onClick={() => handleDelete(params.row.id)}
          >
            删除
          </Button>
        </Stack>
      )
    }
  ];

  return (
    <div className="p-6">
      <div className="flex justify-between mb-4">
        <h1 className="text-2xl font-bold">题库管理</h1>
        <Button
          variant="contained"
          onClick={() => {
            setEditingQuestion(null);
            reset({
              type: 'CHOICE',
              subject: '',
              content: '',
              options: [],
              answer: '',
              explanation: '',
              score: 1.0
            });
            setIsModalVisible(true);
          }}
        >
          新增题目
        </Button>
      </div>

      <div style={{ height: 1000, width: '100%' }}>
        <DataGrid
          rows={questions}
          columns={columns}
          pageSize={10}
          rowsPerPageOptions={[10]}
          disableSelectionOnClick
        />
      </div>

      <Dialog
        open={isModalVisible}
        onClose={() => {
          setIsModalVisible(false);
          setEditingQuestion(null);
          reset();
        }}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>{editingQuestion ? '编辑题目' : '新增题目'}</DialogTitle>
        <QuestionForm
          initialValues={editingQuestion || {
            type: 'CHOICE',
            subject: '',
            content: '',
            options: [],
            answer: '',
            explanation: '',
            score: 1.0
          }}
          onFinish={editingQuestion ? handleUpdate : handleCreate}
          onCancel={() => {
            setIsModalVisible(false);
            setEditingQuestion(null);
            reset();
          }}
          submitText={editingQuestion ? '更新' : '创建'}
        />
      </Dialog>

      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
      >
        <Alert
          onClose={() => setSnackbar({ ...snackbar, open: false })}
          severity={snackbar.severity as any}
          sx={{ width: '100%' }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </div>
  );
}